package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"time"
)

func main() {

	client := redis.NewClient(&redis.Options{
		Addr:     "162.14.70.254:6379",
		Password: "123456",
		DB:       2,
	})

	fmt.Println("连接成功", client)

	// 根据hash的key和field，设置value的值

	client.HSet("user", "name", "tom")
	client.HSet("user", "age", 18)
	client.HSet("user", "address", "北京")
	client.HSet("user", "phone", "123456")
	val, err := client.HGet("user", "name").Result()
	if err != nil {
		fmt.Println("获取失败", err)
	} else {
		fmt.Println("获取成功", val)
	}

	// 根据hash的key，获取所有的field和value
	val2, err := client.HGetAll("user").Result()
	if err != nil {
		fmt.Println("获取失败", err)
	} else {
		fmt.Println("获取成功", val2)
	}

	// 根据hash的key，获取所有的field

	val3, err := client.HKeys("user").Result()
	if err != nil {
		fmt.Println("获取失败", err)
	} else {
		fmt.Println("获取成功field", val3)
	}

	// field字段的值，进行累加
	client.HIncrBy("user", "age", 2)

	val4, err := client.HGetAll("user").Result()
	if err != nil {
		fmt.Println("获取失败", err)
	} else {
		fmt.Println("获取成功", val4)
	}

	var5, _ := client.HMGet("user", "name", "age", "address", "phone").Result()
	fmt.Println("获取成功", var5)

	// 如果field不存在，则创建

	client.HSetNX("user", "friends", "MiracleWong")
	var6, _ := client.HMGet("user", "friends").Result()
	fmt.Println("获取成功", var6)

	// HDel删除一个field的字段值
	client.HDel("user", "friends")
	val7, _ := client.HGetAll("user").Result()
	fmt.Println("获取成功", val7)

	// 查询field是否存在
	val8, _ := client.HExists("user", "friends").Result()
	fmt.Println("获取成功", val8)

	client.Expire("user", 2*time.Hour)

	// ttl
	val9, _ := client.TTL("user").Result()
	fmt.Println("获取成功", val9)

}
